#include "maindefs.h"
#include <stdio.h>
#include "uart_thread.h"
#include "my_uart.h"
#include "my_leds.h"
#include "my_i2c.h"

// This is a "logical" thread that processes messages from the UART
// It is not a "real" thread because there is only the single main thread
// of execution on the PIC because we are not using an RTOS.

int uart_lthread(uart_thread_struct *uptr, int msgtype, int length, unsigned char *msgbuffer) {
#ifndef __USE18F26J50
    unsigned char address;
    unsigned char recvlen;
    if (msgtype == MSGT_OVERRUN) {
    } else if (msgtype == MSGT_UART_DATA) {
        // print the message (this assumes that the message
        // 		was a printable string)
        msgbuffer[length] = '\0'; // null-terminate the array as a string
        
        // Now we would do something with it
        //ToMainLow_sendmsg(length, MSGT_UART_TO_I2C, (void *) msgbuffer);

#if I2C_MASTER
        switch (msgtype)
        {
            case MSGT_GET_SENSOR_DATA:
            {
                address = SENSOR_PIC_READ_ADDRESS;
                recvlen = SENSOR_RECV_LEN;
                break;
            }
            case MSGT_GET_ENCODER_DATA:
            {
                address = MOTOR_PIC_READ_ADDRESS;
                recvlen = ENCODER_RECV_LEN;
                break;
            }
            case MSGT_SET_MOTOR_DATA:
            {
                address = MOTOR_PIC_WRITE_ADDRESS;
                recvlen = MOTOR_RECV_LEN;
                break;
            }
            default:
            {
                return 0;
            }

        }
        i2c_master_set_target(address & 0xFE);
        if (recvlen>0) {
            while(i2c_master_recv(recvlen) != 0);
        } else {
            while(i2c_master_send(length, msgbuffer) != 0);
        }
#else
        start_i2c_slave_reply(length, msgbuffer);
#endif
        
        DBG2_TOGGLE();
    }
#endif
}